package cn.achao.csr.base.entity;

import cn.achao.csr.base.constant.SecurityConstants;
import cn.achao.csr.base.utils.SpringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.SuperBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author: achao
 **/
@Data
@SuperBuilder
@AllArgsConstructor
public abstract class BaseEntity {
    private static final long serialVersionUID = 1L;
    private static final Logger log = LoggerFactory.getLogger(BaseEntity.class);

    private Long id;

    /**
     * 统一序列服务
     * @return 序列编码
     */
    public abstract String sequenceCode();

    /**
     * 无参构造器（默认不生成 id）
     */
    public BaseEntity() {

    }

    /**
     * 带参数的构造器
     * @param generateId 是否生成 id
     */
    protected BaseEntity(Boolean generateId) {
        if (generateId != null && !generateId) {
            generateId();
        }
    }

    /**
     * 生成 id 的逻辑
     */
    private void generateId() {
        log.info("构造器生成id");
        Object bean = SpringUtils.getBean("cn.achao.csr.api.SequenceApi");
        try {
            Method method = bean.getClass().getMethod("getSegmentId", String.class, String.class);
            Object result = method.invoke(bean, this.sequenceCode(), SecurityConstants.INNER);
            if (result instanceof Long) {
                this.id = (Long) result;
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
            log.error("序列服务未启动...");
        }
    }
}
